﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dt261.ble
{

//    3.1.同步成员（android->pc)
//命令地址：0x90
//发送数据单元：

//3.2.同步成员（pc->android)
//命令地址：0x91
//发送数据单元：

//3.3.同步测试记录（android->pc)

//命令地址：0x92
//发送数据单元：

    public enum ErCommandAction
    {
        CommandAction_START = 0x00,
        // 设置参数值命令	0XC1;查询参数值命令	0XC2 ;测试应答	0xC3
        CommandAction_Android2PC = 0XC0,
        CommandAction_Android2PCOK = 0XC1,
        CommandAction_Android2PCError = 0XC2,
        CommandAction_PC2Android = 0XD0,
        CommandAction_PC2AndroidOK = 0XD1,
        CommandAction_PC2AndroidError = 0XD2,

        CommandAction_END = 0xFF

    };
    class ErCommand
    {
        Byte startFlag = 0xFE;//起始标志单元
        Byte commandAddress ;//命令地址(0x01 - 0x9F)
        Byte action ;//应答标志.ErCommandAction
        String json;//数据单元
        Byte endFlag = 0xFF;//结束标志单元

        public ErCommand(byte commandAddress, byte action, string json)
        {
            this.commandAddress = commandAddress;
            this.action = action;
            this.json = json;
        }

        public ErCommand()
        {
            //commandAddress = 0x01;
            //action = 0XD0;
        }


        public  string parseFromHexData(Byte[] data)
        {
            if (data.Length <=4)
            {
                return "命令长度错误";
            }
            else  if (data[0]  != startFlag)
            {
                return "起始标志单元错误";
            }
            else if (data[data.Length-1] != endFlag)
            {
                return "结束标志单元错误";
            }
            else 
            {
                commandAddress = data[1];
                action = data[2];
                json = new UTF8Encoding().GetString(data,3, data.Length - 4);
                return null;
            }
        }


        public Byte[] getHex()
        {

            

            byte[] jsondata = new UTF8Encoding().GetBytes(json);
            int sendCount = jsondata.Length;
            Byte[] reply = new Byte[4+ sendCount];
            reply[0] = startFlag;
            reply[1] = commandAddress;
            reply[2] = action;

            Array.Copy(jsondata, 0, reply, 3, sendCount);

            reply[sendCount+3] = endFlag;

            return reply;

        }
        public Byte[]  getReply(bool isok = true)
        {
            Byte[] reply = new Byte[4];
            reply[0] = startFlag;
            reply[1] = commandAddress;
            reply[2] = (Byte)( isok ? (action + 0x01) : (action + 0x02));
            reply[3] = endFlag;

            return reply;

        }
    }
}
